package com.syyo.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.syyo.common.domain.ResultVo;
import com.syyo.common.to.es.SkuEsModel;
import com.syyo.common.utils.MyListUtils;
import com.syyo.gulimall.search.config.GulimallElasticsearchConfig;
import com.syyo.gulimall.search.constant.EsConstant;
import com.syyo.gulimall.search.feign.ProductFeign;
import com.syyo.gulimall.search.service.MallSearchService;
import com.syyo.gulimall.search.vo.AttrRespVo;
import com.syyo.gulimall.search.vo.BrandVo;
import com.syyo.gulimall.search.vo.SearchParam;
import com.syyo.gulimall.search.vo.SearchResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ author: wang
 * @ date: 2021/3/30 17:06
 * @ Description:
 */
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient esClient;

    @Autowired
    private ProductFeign productFeign;

    private static final String SEARCH_URL = "http://search.gulimall.com/list.html?"; // 检索服务器地址

    /**
     * @param param 检索的所有参数
     * @return
     */
    @Override
    public SearchResult search(SearchParam param) {
        // 构建es的dsl语句
        SearchResult searchResult = null;

        // 1.准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);

        try {
            // 2.执行检索请求
            SearchResponse response = esClient.search(searchRequest, GulimallElasticsearchConfig.COMMON_OPTION);

            // 3.分析响应数据
            searchResult = buildSearchResult(response, param);

        } catch (IOException e) {
            e.printStackTrace();
        }


        return searchResult;
    }

    /**
     * 构建请求
     * # 检索商品
     * # must 模糊匹配
     * # filter 过滤（按照属性、分类、品牌、库存、价格区间）
     * # sort 排序
     * # from size 分页
     * # highlight 高亮
     */
    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        /**
         * must 模糊匹配 filter 过滤（按照属性、分类、品牌、库存、价格区间）
         */
        // 1 构建 bool-query
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // 1.1 must
        String keyword = param.getKeyword();
        if (!StringUtils.isEmpty(keyword)) {
            boolQuery.must(QueryBuilders.matchQuery("skuTitle", keyword));
        }
        // 1.2 构建 bool-filter  ,按照三级分类id查询
        if (param.getCatalog3Id() != null) {
            boolQuery.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        // 1.3 构建 bool-filter  ,按照品牌id查询
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQuery.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
        }
        // 1.4 构建 bool-filter  ,按照库存
        if (param.getHasStock() != null) {
            boolQuery.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }

        // 1.5 构建 bool-filter  ,按照价格区间
        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            /**
             * 1_500  _500  500_
             *
             *    "range": {
             *      "skuPrice": {
             *      "gte": 0,
             *      "lte": 6000
             *      }
             *    }
             *
             */
            RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");

            if (s.length == 2) {
                if ("".equals(s[0])) {
                    // _500
                    rangeQuery.lte(s[1]);
                } else {
                    // 1_500
                    rangeQuery.gte(s[0]).lte(s[1]);
                }
            } else if (s.length == 1) {
                // 500_
                rangeQuery.gte(s[0]);
            }
            boolQuery.filter(rangeQuery);
        }


        // 1.6 构建 bool-filter  ,按照属性查询
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {
            for (String attr : param.getAttrs()) {
                // attrs=2_5寸:6寸
                BoolQueryBuilder nestedBoolQuery = QueryBuilders.boolQuery();
                String[] s = attr.split("_");
                String attrId = s[0];// 属性id
                String[] attrValues = s[1].split(":");//多个属性值
                nestedBoolQuery.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                nestedBoolQuery.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
                // 每一个必须都得生成nested嵌入式查询
                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", nestedBoolQuery, ScoreMode.None);
                boolQuery.filter(nestedQuery);
            }
        }

        // 把所有的条件进行封装
        searchSourceBuilder.query(boolQuery);
        /**
         * sort 排序
         * from size 分页
         * highlight 高亮
         */
        // 2.1 排序
        if (!StringUtils.isEmpty(param.getSort())) {
            // sort=saleCount_asc/desc
            String[] s = param.getSort().split("_");
            SortOrder order = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(s[0], order);
        }
        // 2.2 分页
        // from = (pageNum - 1) * pageSize
        searchSourceBuilder.from((param.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        // 2.3 高亮
        if (!StringUtils.isEmpty(keyword)) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("skuTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        /**
         * agg聚合
         */
        // 1.品牌聚合
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
        brand_agg.field("brandId").size(50);

        // 1.1品牌聚合的子聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);

        // 2.分类聚合
        TermsAggregationBuilder catelog_agg = AggregationBuilders.terms("catelog_agg");
        catelog_agg.field("catalogId").size(20);
        // 2.1分类的子聚合
        catelog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));
        searchSourceBuilder.aggregation(catelog_agg);

        // 3.属性聚合
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        // 3.1聚合当前所有的attrId
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        // 3.2聚合当前所有的attrName
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        // 3.3聚合当前所有的attrValue
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));


        attr_agg.subAggregation(attr_id_agg);
        searchSourceBuilder.aggregation(attr_agg);

        String s = searchSourceBuilder.toString();
        System.out.println("构建的dsl： " + s);

        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDE}, searchSourceBuilder);
        return searchRequest;
    }

    /**
     * 处理响应结果
     *
     * @param response
     * @return
     */
    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();
        // 1.返回所有查询到的商品
        SearchHits hits = response.getHits();
        List<SkuEsModel> esModels = new ArrayList<>();
        if (hits.getHits() != null && hits.getHits().length > 0) {
            for (SearchHit hit : hits.getHits()) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);

                if (!StringUtils.isEmpty(param.getKeyword())) {
                    // 处理高亮标题
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String string = skuTitle.getFragments()[0].string();
                    esModel.setSkuTitle(string);
                }
                esModels.add(esModel);
            }

        }
        result.setProducts(esModels);


        // 2.当前所有商品涉及到的品牌信息
        ParsedLongTerms brand_agg = response.getAggregations().get("brand_agg");
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();

            //  品牌id
            String keyAsString = bucket.getKeyAsString();

            //  品牌名称
            ParsedStringTerms brand_name_agg = bucket.getAggregations().get("brand_name_agg");
            String brandName = brand_name_agg.getBuckets().get(0).getKeyAsString();
            // 品牌logo
            ParsedStringTerms brand_img_agg = bucket.getAggregations().get("brand_img_agg");
            String brandImg = brand_img_agg.getBuckets().get(0).getKeyAsString();

            // todo brandImg和brandName在es 存反了 由于数据存反了，所以也反着赋值
            brandVo.setBrandId(Long.parseLong(keyAsString));
            brandVo.setBrandImg(brandName);
            brandVo.setBrandName(brandImg);

            brandVos.add(brandVo);
        }

        result.setBrands(brandVos);


        // 3.当前所有商品涉及到的分类信息
        ParsedLongTerms catelog_agg = response.getAggregations().get("catelog_agg");
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        for (Terms.Bucket bucket : catelog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();

            //  分类id
            String keyAsString = bucket.getKeyAsString();

            //  分类名称
            ParsedStringTerms catalog_name_agg = bucket.getAggregations().get("catalog_name_agg");
            String catalogName = catalog_name_agg.getBuckets().get(0).getKeyAsString();

            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            catalogVo.setCatalogName(catalogName);
            catalogVos.add(catalogVo);
        }

        result.setCatalogs(catalogVos);


        // 4.当前所有商品涉及到的属性信息
        ParsedNested attr_agg = response.getAggregations().get("attr_agg");
        ParsedLongTerms attr_id_agg = attr_agg.getAggregations().get("attr_id_agg");
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();


        for (Terms.Bucket bucket : attr_id_agg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 属性id
            long attrId = bucket.getKeyAsNumber().longValue();


            // 属性名称
            ParsedStringTerms attr_name_agg = bucket.getAggregations().get("attr_name_agg");
            String attrName = attr_name_agg.getBuckets().get(0).getKeyAsString();

            // 属性值
            ParsedStringTerms attr_value_agg = bucket.getAggregations().get("attr_value_agg");
            List<String> attrValues = attr_value_agg.getBuckets().stream().map(item -> {
                String keyAsString = item.getKeyAsString();
                return keyAsString;
            }).collect(Collectors.toList());

            attrVo.setAttrId(attrId);
            attrVo.setAttrName(attrName);
            attrVo.setAttrValue(attrValues);

            attrVos.add(attrVo);
        }

        result.setAttrs(attrVos);

        // 5.分页信息

        long totle = hits.getTotalHits().value;
        result.setTotal(totle);

        long totlePage = totle % EsConstant.PRODUCT_PAGESIZE == 0 ? totle / EsConstant.PRODUCT_PAGESIZE : (totle / EsConstant.PRODUCT_PAGESIZE) + 1;
        int page = (int) totlePage;
        result.setTotalPage(page);
        result.setPageNum(param.getPageNum());

        List<Integer> pageNavs = new ArrayList<>();
        for (int i = 1; i <= page; i++) {
            pageNavs.add(i);
        }
        result.setPageNavs(pageNavs);

        // 6.处理面包屑数据
        if (MyListUtils.isNotEmpty(param.getAttrs())) {
            List<SearchResult.NavVo> navVoList = param.getAttrs().stream().map(attr -> {
                // 分析每一个attr的值  attrs=2_5寸:6寸
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                String[] s = attr.split("_");
                navVo.setNavValue(s[1]);
                result.getAttrIds().add(Long.parseLong(s[0]));//被选中的属性id
                ResultVo r = productFeign.findOne(Integer.parseInt(s[0]));
                if (r.getCode() == 20000) {
                    // 先将obj对象转成json字符串，然后再使用TypeReference来转成对应的对象
                    String jsonString = JSON.toJSONString(r.getData());
                    AttrRespVo attrRespVo = JSON.parseObject(jsonString, new TypeReference<AttrRespVo>() {
                    });
                    navVo.setNavName(attrRespVo.getAttrName());
                } else {
                    navVo.setNavName(s[0]);
                }
                String replace = replaceQueryString(param, attr, "attrs");
                navVo.setLink(SEARCH_URL + replace);
                return navVo;
            }).collect(Collectors.toList());
            result.setNavs(navVoList);
        }

        // 7.品牌，分类
        if (MyListUtils.isNotEmpty(param.getBrandId())) {
            List<SearchResult.NavVo> navs = result.getNavs();
            SearchResult.NavVo navVo = new SearchResult.NavVo();

            navVo.setNavName("品牌");

            ResultVo r = productFeign.brandInfos(param.getBrandId());
            if (r.getCode() == 20000) {
                // 先将obj对象转成json字符串，然后再使用TypeReference来转成对应的对象
                String jsonString = JSON.toJSONString(r.getData());
                List<BrandVo> brands = JSON.parseObject(jsonString, new TypeReference<List<BrandVo>>() {
                });
                StringBuffer stringBuffer = new StringBuffer();
                String replace = "";
                for (BrandVo brand : brands) {
                    stringBuffer.append(brand.getName() + ";");

                    replace = replaceQueryString(param, brand.getBrandId() + "", "brandId");
                }
                navVo.setNavValue(stringBuffer.toString());
                navVo.setLink(SEARCH_URL + replace);
            }
            navs.add(navVo);
            result.setNavs(navs);
        }
        // 处理面包屑只有一个条件参数的问题
        if (result.getNavs().size() == 1) {
            SearchResult.NavVo navVo = result.getNavs().get(0);
            navVo.setLink(SEARCH_URL);
        }

        return result;
    }

    private String replaceQueryString(SearchParam param, String value, String key) {
        String encode = "";

        try {
            encode = URLEncoder.encode(value, "UTF-8");
            // 浏览器转码，把空格转成 '%20'
            // java转码， 把空格转成 '+'
            encode = encode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 取消了这个面包屑以后，我们要跳转的地方
        return param.get_queryString().replace("&" + key + "=" + encode, "");
    }
}
